<?php


namespace app\home\controller;

use app\common\model\User;
use think\facade\Db;

class Wechat
{

    public function checkSignature($signature,$timestamp,$nonce,$echostr)
    {
        $token = "v6tn721er81af5rq84";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    protected function getAccessToken()
    {
        $appid = "wx7f03c3f9e1c33305";
        $secret = "04a4c66355666f5cd40963a2aaa64ee8";

        $URL ="https://api.weixin.qq.com/cgi-bin/token?appid=".$appid."&secret=".$secret."&grant_type=client_credential";
        $rel = curlData($URL);
        return $rel["access_token"];
    }

    public function reqCode()
    {
        $getAccessToken =  $this->getAccessToken();
        $URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" .$getAccessToken;

        $rand =rand(1,100000);
        $list = array(
            'action_name'  => 'QR_SCENE',
            'action_info' =>  array(
                'scene' => array(
                    'scene_id'  => $rand,
                ),
            ),
        );
        $rel = curlData($URL,json_encode($list) ,"POST");

        // 通过ticket换取二维码
        $codeURL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" .urlencode($rel['ticket']);
        return json(["code" =>0 ,"url" =>$codeURL,'debug' =>cache("uid")]);
    }
    public function wxlogin()
    {
        $xml = file_get_contents("php://input");
        $data = xmlToArray($xml);

        $signature = input("signature");
        $timestamp = input("timestamp");
        $nonce = input("nonce");
        $echostr = input("echostr");


        if ($this->checkSignature($signature,$timestamp,$nonce,$echostr) == true){
            echo $echostr;
        }else{
            return json(["code" => 0 ,"msg" =>"非法请求"]);
        }

        if (isset($data["Ticket"])) {
            $getAccessToken = $this->getAccessToken();
            $getUrl = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" . $getAccessToken;

            $userList = [
                "user_list" => [
                    [
                        "openid" => $data["FromUserName"],
                        "lang" => "zh_CN"
                    ]
                ]
            ];
            $rel = curlData($getUrl, json_encode($userList, true), "POST");

            $userInfo = $rel["user_info_list"][0];

            $createUserData["username"] = $userInfo["nickname"];
            $createUserData["avatar"] = $userInfo["headimgurl"];
            $createUserData["openid"] = $userInfo["openid"];
            $createUserData["group_id"] = 2;

            $xmlData["ToUserName"] = $userInfo["openid"];
            $xmlData["FromUserName"] = "gh_57d79dd5ffc0";
            $xmlData["CreateTime"] = time();
            $xmlData["MsgType"] = "text";

            $uid = Db::name("user")->where("openid", $userInfo["openid"])->value("uid");

            $xmlData["Content"] = "登录成功";
            $cacheKey = md5($userInfo["openid"] .time() .rand(10000,99999));

            if ($uid) {
                cache($cacheKey,$uid,180);
                cache("loginCacheKey",$cacheKey,180);
            }else{
                $createUser = User::create($createUserData);
                if ($createUser) {
                    $uid =  $createUser->uid;
                    cache($cacheKey,$uid,180);
                    cache("loginCacheKey",$cacheKey,180);
                }else{
                    $xmlData["Content"] = "登录失败";
                }
            }
            return xml($xmlData, 200, [], ['root_node' => 'xml']);
        }

    }

    public function checkSessionKey()
    {
        if (cache("loginCacheKey")){
            return  json(["code" =>1, "data" =>cache("loginCacheKey")]);
        }
        return  json(["code" =>0, "msg" =>"用户未扫二维码！"]);
    }

    public function createSession()
    {
        $sessionKey = input("sessionKey");

        if ($sessionKey == cache("loginCacheKey")){
            cache("loginCacheKey",NULL);
            session("UID",cache("$sessionKey"));
            return json(["code" => 1,"msg" =>"登录成功"]);
        }
        return json(["code" => 0,"msg" =>"登录失败"]);
    }

    public function wxSendMember($openid,$templateId, array $first,array $keyword1,array $keyword2, array $keyword3,array $remark)
    {
        $AccessToken = $this->getAccessToken();
        $URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" .$AccessToken;

        $data = [
            "touser" => $openid,
            "template_id" => $templateId,
            "data" =>["first" => $first, "keyword1" => $keyword1, "keyword2"=> $keyword2, "keyword3"=> $keyword3, "remark"=> $remark]
        ];

        $rel = curlData($URL,json_encode($data, true) ,"POST");
        if ($rel){
            return json(["code" =>1,"msg" => "已微信通知用户投稿成功"]);
        }
    }
    public function a()
    {
        $openid = "o_MmO08-KweMWIQRapBSEvhwzeYQ";
        $templateId = "U6ptqmnXmBRZzOc1J2UuBMV49mG5ZQqOxv-MVqYiMUU";
        $first =  ["value" =>"恭喜你购买成功","color" => "#173177" ];
        $keyword1 =  ["value" =>"恭喜你购买成功","color" => "#173177" ];
        $keyword2 =  ["value" =>"恭喜你购买成功","color" => "#173177" ];
        $keyword3 =  ["value" =>"恭喜你购买成功","color" => "#173177" ];
        $remark =  ["value" =>"恭喜你购买成功","color" => "#173177" ];

        $this->wxSendMember($openid,$templateId, $first,$keyword1,$keyword2, $keyword3,$remark);
    }
}